angular.module("App")
    .service('apiService', ['$http', '$window', '$q', '$rootScope','$timeout','appConfig', 'utils','cookie',
        function ($http, $window, $q, $rootScope,$timeout,appConfig, utils,cookie) {
            this.domain = "http://" + appConfig.host + ":" + appConfig.port;
            this.serverUrl = this.domain + "/SJPlatFormWebTest";
            $rootScope.serverUrl = this.serverUrl;
            this.uploadUrl = this.serverUrl + "/actionapi/Files/Upload";  //上传路径
            //请求参数处理
            this.handleParams = function (params) {
                params = params ? params : {};
                params.key = cookie.getUserid();
                params.blackbox = cookie.getjm();
                return params;
            };
            //header参数处理------------------
            this.handleConfig = function (httpConfig) {
                httpConfig = httpConfig ? httpConfig : {};

                if (!httpConfig.headers) {
                    httpConfig.headers = {
                        appId: appConfig.appId
                    };
                } else {
                    httpConfig.headers["appId"] = appConfig.appId;
                }
                return httpConfig;
            };


            //创建post请求-------------
            this.apiPost = function (api, params) {
                var cookieval = cookie.getTimeCookie();
                var userid = cookie.getUserid();
                if (!angular.isDefined(cookieval) && !angular.equals(null, userid)) {
                    getTimestamp($rootScope.serverUrl,userid);
                }
                var deferred = $q.defer();
                var url = this.serverUrl + api;
                var allParams = this.handleParams(params);
                $http.post(url, allParams).success(
                    function (data) {
                        deferred.resolve(data);
                    }
                ).error(function (err) {
                    $rootScope.tips.showError("请求失败");
                    $rootScope.hideLoading();
                    deferred.reject(err);
                });
                return deferred.promise;
            };


            //退出
            this.loginOut = function(params, config) {
                var api = "/actionapi/Login/LoginOut";
                return this.apiPost(api, params, config);
            };


            //获取时间戳
            function getTimestamp(serverUrl,userid) {
                $.ajax({
                    type:"POST",
                    url:serverUrl + "/actionapi/Login/GetTimeStamp",
                    async: false,
                    success:function(result){
                        cookie.setCookie(result);
                        cookie.jm(userid, result);
                    },
                    failure:function (result) {
                        return false;
                    }
                });
            }
        }
    ]);